package com.diver.flinkdemo.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by wenjun on 2018/8/1.
 */
public class GaoDeMapUtil {
    private static Logger logger = LoggerFactory.getLogger(GaoDeMapUtil.class);
    /**
     * 高德地图请求秘钥
     */
    private static final String KEY = CommonResource.GAODE_API_KEY;
    /**
     * 返回值类型
     */
    private static final String OUTPUT = "JSON";
    /**
     * 根据地名获取高德经纬度
     */
    private static final String GET_LNG_LAT_URL = "http://restapi.amap.com/v3/geocode/geo";
    /**
     * 根据高德经纬度获取地名
     */
    private static final String GET_ADDRESS_URL = "https://restapi.amap.com/v3/geocode/regeo";

    /**
     * 根据高德经纬度获取地址信息
     *
     * @param gdLon 高德地图经度
     * @param gdLat 高德地图纬度
     * @return
     */
    public static String getAddressByLonLat(String gdLon, String gdLat) {

        String location = gdLon + "," + gdLat;
        Map<String, String> params = new HashMap<>();
        params.put("location", location);

        // Map<String, String> result = new HashMap<>();
        try {
            // 拼装url
            String url = jointUrl(params, OUTPUT, KEY, GET_ADDRESS_URL);
            // 调用高德SDK
            String jsonResult = HttpUrlClient.doPost(url, null);
            logger.info("调用高德经纬度转地址接口返回:"+jsonResult);
            // 解析Json字符串,获取城市名称
            JSONObject jsonObject = JSON.parseObject(jsonResult);
            String regeocode = jsonObject.getString("regeocode");
            JSONObject regeocodeObj = JSON.parseObject(regeocode);
            String address = regeocodeObj.getString("formatted_address");
            // 组装结果
            return address;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据地址信息获取高德经纬度
     *
     * @param address 地址信息
     * @return [lng, lat]
     */
    public static Map<String, String> getLngLatByAddress(String address) {
        if (!StringUtils.isBlank(address)) {
            Map<String, String> params = new HashMap<>();
            params.put("key",KEY);
            params.put("address", address);
            try {
                // 拼装url
               // String url = jointUrl(params, OUTPUT, KEY, GET_LNG_LAT_URL);
                // 调用高德地图SDK
                String jsonResult = HttpUrlClient.doPost(GET_LNG_LAT_URL, params);
                // 解析JSON字符串,取到高德经纬度
                JSONObject jsonObject = JSON.parseObject(jsonResult);
                if ("1".equals(jsonObject.get("status"))) {
                    JSONArray geocodes = jsonObject.getJSONArray("geocodes");
                    if (null != geocodes && !geocodes.isEmpty()) {
                        String geocode = JSON.toJSONString(geocodes.get(0));
                        JSONObject geocodeObj = JSON.parseObject(geocode);
                        Map<String, String> location = new HashMap<>();
                        String lngAndLat = geocodeObj.getString("location");
                        if (StringUtils.isNotBlank(lngAndLat)) {
                            String lng = lngAndLat.split(",")[0];
                            String lat = lngAndLat.split(",")[1];
                            location.put("lng", lng);
                            location.put("lat", lat);
                            return location;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 拼接请求字符串
     *
     * @param params
     * @param output
     * @param key
     * @param url
     * @return
     * @throws IOException
     */
    private static String jointUrl(Map<String, String> params, String output, String key, String url) throws IOException {
        StringBuilder baseUrl = new StringBuilder();
        baseUrl.append(url);
        baseUrl.append("?key=").append(key);
        if (params!=null){
            Set<Map.Entry<String, String>> entrys = params.entrySet();
            for (Map.Entry<String, String> param : entrys) {
                baseUrl.append("&");
                baseUrl.append(param.getKey()).append("=").append(param.getValue());
            }
        }

        return baseUrl.toString();
    }

    public static void main(String[] args) {
        System.out.println(getLngLatByAddress("四川省成都市双流区中和街道王府春天花园"));
//        System.out.println(getAddressByLonLat("104.08998", "30.553383"));
    }
}
